package Comp355Final.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

import android.R.color;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * The GUI for bookshelf
 * @author chung
 *
 */
public class GUIBookShelfChSelect extends Activity {
	private Utility myutility; 
	private ArrayList<String> path_list = new ArrayList<String>();
	private String charset="UTF-8";
	private FileIO fileio;
    private ArrayList<String> book_list;
    private ArrayList<String> cover_list = new ArrayList<String>();
    private ArrayList<String> pathlist_withoutExt = new ArrayList<String>();
    private Config myconfig;
    private String Book_name;
   // private String Book_url;
    public String getBookName()
    {
    	return Book_name;
    }
    public String getCharset()
    {
    	return charset;
    }
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        Book_name=extras.getString("Book_name");
        //String Book_url=extras.getString("Book_url");
        charset = extras.getString("Current_Charset");

        //Utility.quick_dialog("Testing", this);
        fileio = new FileIO(Book_name);
        
        myutility = new Utility();
        //Scan the books folder
        book_list = fileio.scan_folder();
        book_list = fileio.filter_allExt(book_list);
       // Utility.quick_dialog("Testing"+book_list.size(), this);
        cover_list = fileio.scan_img_folder();
        cover_list = fileio.filter_ImgExt(cover_list);
        //Print out all books

        for(int i=0;i<book_list.size();i++)
        {
        	path_list.add(book_list.get(i));
        }
        if(book_list.size()==0)
        {
        	Utility.quick_dialog("There is no chapter in this book.", this);
        }
        for(int i=0;i<path_list.size();i++)
        {
        	//Read out the details
        }
        ScrollView scllview = new ScrollView(this);
        ScrollView.LayoutParams scllview_param = new ScrollView.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
        scllview.setBackgroundColor(Color.WHITE);
        myconfig = new Config(this);
        
        scllview.setBackgroundDrawable(myconfig.return_bg());
        ArrayList<LinearLayout> panel_array = new ArrayList<LinearLayout>();
        LinearLayout Llay = new LinearLayout(this);
        LinearLayout.LayoutParams Llay_param = new LinearLayout.LayoutParams(
        		ViewGroup.LayoutParams.FILL_PARENT,
        		ViewGroup.LayoutParams.FILL_PARENT);
    	Llay.setOrientation(LinearLayout.VERTICAL);
    	pathlist_withoutExt = Utility.replace_extension(path_list);
    	ArrayList<String> coverlist_withoutExt = Utility.replace_extension(cover_list);
    	for(int i=0;i<pathlist_withoutExt.size();i++)
    	{
    		pathlist_withoutExt.set(i,pathlist_withoutExt.get(i).replace(fileio.get_sdcard_dest(), ""));
    	}
    	for(int i=0;i<coverlist_withoutExt.size();i++)
    	{
    		coverlist_withoutExt.set(i,coverlist_withoutExt.get(i).replace(fileio.get_sdcard_dest()+"covers/", ""));
    	}
    	ViewGroup.LayoutParams img_panel_param = new ViewGroup.LayoutParams(60,60);
        for(int i=0;i<path_list.size();i++)
        {
        	LinearLayout tmp_panel = new LinearLayout(this);
            LinearLayout.LayoutParams tmp_panel_param = new LinearLayout.LayoutParams(
            		ViewGroup.LayoutParams.FILL_PARENT,
            		ViewGroup.LayoutParams.WRAP_CONTENT);
            tmp_panel.setOrientation(LinearLayout.HORIZONTAL);
        	TextView tmptxt_view = new TextView(this);
        	ImageView tmpimg_view = new ImageView(this);
        	tmptxt_view.setTextColor(Color.BLACK);
        	tmptxt_view.setText(pathlist_withoutExt.get(i));
        	
        	/*
        	boolean have_cover = false;
        
        	for(int j=0;j<coverlist_withoutExt.size();j++)
        	{
		        	if(coverlist_withoutExt.get(j).equals(pathlist_withoutExt.get(i)))
		        	{ 
		        		have_cover = true;
		        		BitmapFactory.Options options = new BitmapFactory.Options();
		        		options.inSampleSize = 1;
		        		BitmapDrawable default_cover = new BitmapDrawable(BitmapFactory.decodeFile(this.cover_list.get(j), options));

		        		tmpimg_view.setScaleType(ImageView.ScaleType.CENTER_CROP);
		        		//tmpimg_view.setAdjustViewBounds(true);
		        		//tmpimg_view.setMaxHeight(5);
		        		//tmpimg_view.setMaxWidth(5);
		        		
		        		//tmpimg_view.setBackgroundDrawable(default_cover);
		        	}
        	}
        	*/
        	//if(!have_cover)
        	//{
        		//BitmapDrawable default_cover = new BitmapDrawable(BitmapFactory.decodeResource(this.getResources(), R.drawable.nocover));
        		//tmpimg_view.setBackgroundDrawable(default_cover);
        	String file_ext = FileIO.getFileExt(path_list.get(i));
        	
        	if(file_ext.equals("png"))
        		tmpimg_view.setImageResource(R.drawable.mimepng);
        	else if(file_ext.equals("gif"))
        		tmpimg_view.setImageResource(R.drawable.mimegif);
        	else if(file_ext.equals("jpg"))
				tmpimg_view.setImageResource(R.drawable.mimejpg);
        	else
        		tmpimg_view.setImageResource(R.drawable.mimetxt);
        	
        	//}
        	
        	tmp_panel.setClickable(true);
        	tmp_panel.setLongClickable(true);
        	BookShelfchClickListener cl = new BookShelfchClickListener(GUIBookShelfChSelect.this,tmptxt_view,path_list.get(i),this.myconfig,pathlist_withoutExt.get(i),this.Book_name);
        	tmp_panel.setOnClickListener(cl);
        	tmp_panel.setId(panel_array.size());
        	PanelOnTouchListener tmp_panel_listener = new PanelOnTouchListener(tmptxt_view);
        	tmp_panel.setOnTouchListener(tmp_panel_listener);

        	registerForContextMenu(tmp_panel);
        	
        	tmp_panel.addView(tmpimg_view,img_panel_param);
        	tmp_panel.addView(tmptxt_view);
        	
        	//Show up in the panel
        	panel_array.add(tmp_panel);
        	Llay.addView(tmp_panel,tmp_panel_param);
        	
        }
        //tv.append(tmp_print);
        //
        
        
        
       // LinearLayout Llay  = (LinearLayout) this.findViewById(R.id.lnr_view);
        
      //Find the view by its id

        //String tmp_str = text.toString();
        //tv.setText("Test");
      
     // Llay.addView(tv);

      //  setContentView(R.layout.main);
       // TextRunnable tr = new TextRunnable(tv, "123");
        //tv.setText("Test");
      //  mHandler.postDelayed(tr, 10 * 1000);
        this.setTitle("BookShelf - "+Book_name);
       scllview.addView(Llay, Llay_param);
       this.setContentView(scllview, scllview_param);

    }
    private int panel_id_selected=0;
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
    	panel_id_selected=v.getId();
    	menu.setHeaderTitle(path_list.get(panel_id_selected).replace(fileio.get_sdcard_dest(), ""));
    	
    	
       // Toast.makeText(
       //         GUIMain.this,
      //          String.valueOf(panel_id_selected),
       //         Toast.LENGTH_LONG).show();
    	menu.add(0, 0, 0, "Read");
    	menu.add(0, 1, 1, "Delete");
    	menu.add(0, 2, 3, "Details");
    	menu.add(0, 3, 2, "Rename");
    	super.onCreateContextMenu(menu, v, menuInfo);
    }
    
    @Override 
    public boolean onContextItemSelected(MenuItem item) { 
    	switch(item.getItemId()){
    	case 0:
    		BookShelfchClickListener.go_toViewer(this,this.path_list.get(panel_id_selected),pathlist_withoutExt.get(panel_id_selected),Book_name);
    		break;
    	case 1:
    		final AlertDialog alertDialog = Utility.getAlertDialog("Please select.","Are you sure to delete this file?",this,new DiologClickListener(this, fileio,this.path_list.get(panel_id_selected),this)); 
    		alertDialog.show(); 
    		break;
    	case 2:   
    		//Toast.makeText(this, "Option 2", Toast.LENGTH_LONG).show();   
			Intent int_ent = new Intent(this, GUIFileDetail.class);
			//Intent int_ent = new Intent(parent, LargeImageScroller.class);
			int_ent.putExtra("filepath", path_list.get(panel_id_selected));
			//book_folder
			this.startActivity(int_ent);
    		break;
    	case 3:
    		this.showDialog(DIALOG_RENAME_ENTRY);
    		break;
    		}     
    	return super.onContextItemSelected(item);
    	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) { 
    	ArrayList<String> charset_code = this.myutility.return_charset_code();
       SubMenu submenu_charset = menu.addSubMenu(0, charset_code.size(), 0, "Charset").setIcon(android.R.drawable.ic_menu_view); 
       
       for(int i=0;i<charset_code.size();i++)
       {
    	   submenu_charset.add(0,i ,0,charset_code.get(i));
       }
       SubMenu More_functions = menu.addSubMenu(0, charset_code.size(), 5, "More Functions").setIcon(android.R.drawable.ic_menu_more);
       menu.add(0, charset_code.size()+1, 3, "Return to BookShelf").setIcon(android.R.drawable.ic_menu_revert); 
      
       menu.add(0, charset_code.size()+2, 1, "Setting").setIcon(android.R.drawable.ic_menu_preferences);
       menu.add(0, charset_code.size()+3, 2, "Gather from Internet").setIcon(android.R.drawable.ic_menu_search);
   
       More_functions.add(0, charset_code.size()+4, 0, "Download file from SDCard");
       More_functions.add(0, charset_code.size()+5, 1, "Refresh the bookshelf");
       return super.onCreateOptionsMenu(menu); 
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) { 
    	ArrayList<String> charset_code = this.myutility.return_charset_code();
    	for(int i = 0;i<charset_code.size();i++)
    	{
    		if(i==item.getItemId())
    		{
    			this.charset=charset_code.get(i);
    	        Utility.quick_dialog("Charset has changed to "+charset, this);
    			return super.onOptionsItemSelected(item); 
    		}
    	}
    	
    	if(item.getItemId()==charset_code.size())
    	{
    		
    	}
    	else if(item.getItemId()==(charset_code.size()+1))
    	{
    		Intent int_ent = new Intent(this, GUIBookShelfBkSelect.class);
    		this.startActivity(int_ent);
    		finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+2))
    	{
    		//Utility.quick_dialog("Settings clicked", this);
    		Intent int_ent = new Intent(this, GUIConfig.class);
    		this.startActivity(int_ent);
    		//finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+3))
    	{
    		Intent int_ent = new Intent(this, GUIInternetList.class);
    		this.startActivity(int_ent);
    		//finish();
    	}
    	else if(item.getItemId()==(charset_code.size()+4))
    	{
    		Intent int_ent = new Intent(this, GUIBookSelector.class);
    		this.startActivity(int_ent);
    	}
    	else if(item.getItemId()==(charset_code.size()+5))
    	{
    		this.refresh_me();
    	}

    return super.onOptionsItemSelected(item); 
    } 
     public String get_currCharset()
     {
		return charset;
     }
     private static final int DIALOG_RENAME_ENTRY = 8;
     @Override   
     protected Dialog onCreateDialog(int id) {
     	switch(id){
         case DIALOG_RENAME_ENTRY:
         	// This example shows how to add a custom layout to an AlertDialog
         	LayoutInflater factory2 = LayoutInflater.from(this);
         	final EditText search_box2 = new EditText(this);
         	final View textEntryView2 = search_box2;
         	return new AlertDialog.Builder(GUIBookShelfChSelect.this)
         	//.setIconAttribute(android.R.drawable.)
         	.setTitle("Rename the file")
         	.setView(textEntryView2)
         	.setPositiveButton("ok", new DialogInterface.OnClickListener() {
         		public void onClick(DialogInterface dialog, int whichButton) {
         				String tmp_str = search_box2.getText().toString();
         				if(!tmp_str.equals(""))
         				{
         					if(fileio.reNameFolderOrFile(GUIBookShelfChSelect.this.path_list.get(panel_id_selected), Book_name+"/"+tmp_str))
     						{
         						Utility.quick_dialog("Rename is succeed.", GUIBookShelfChSelect.this);
         						GUIBookShelfChSelect.this.refresh_me();
     						}
        					else
        					{
        						Utility.quick_dialog("Folder or file with the same name may existed.", GUIBookShelfChSelect.this);
        					}
         				}
         				else
         				{
         					Utility.quick_dialog("You must enter valid name.", GUIBookShelfChSelect.this);
         				}
         			} 
         		})
         		.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
         			public void onClick(DialogInterface dialog, int whichButton) {
         				search_box2.setText("");
         				/* User clicked cancel so do some stuff */
         				} 
         			})
         			.create();	
 
     	}
     	return null;
     	}
     public void refresh_me()
     {
 		Intent int_ent = new Intent(this, GUIBookShelfChSelect.class);
		int_ent.putExtra("Current_Charset", this.charset);
		int_ent.putExtra("Book_name", this.Book_name);
		this.startActivity(int_ent);
		this.finish();
     }
     private boolean activity_restarted=false;
     @Override
     public void onResume() {
     	if(activity_restarted)
     	{
    	 this.refresh_me();
    	activity_restarted=false;
     	}
    	 super.onResume();
     }
     @Override
     public void onPause() {
     	activity_restarted=true;
     	super.onPause();
     }
     
     @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
    	 System.out.println(keyCode);
    	 if ((keyCode == KeyEvent.KEYCODE_BACK)) {
    		 Bundle bundle = new Bundle();  
    		bundle.putString("Current_Charset", this.charset);  
    	        Intent retun_intent = new Intent();
    	        retun_intent.putExtras(bundle);
    	        this.setResult(0,retun_intent);
    	       // this.finish();
    	 }
		return super.onKeyDown(keyCode, event);
     }


}